package com.isscollage.quartz;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.isscollage.dao.OrderDao;
import com.isscollage.dao.TicketDao;
import com.isscollage.entity.Ticket;
import com.isscollage.entity.TicketLog;
import com.isscollage.entity.TicketOrder;
import com.isscollage.utils.UUIDUtils;

@Service
public class TicketDailyService {
	@Autowired
	private TicketDao ticketDao;
	@Autowired
	private OrderDao orderDao;
	/**
	 * 实现每天早晨7点投放15天以内的车票信息
	 */
	public void putInTicket(){
		System.out.println("启动定时器。。。");
		List<Ticket> tickets=ticketDao.searchAll();
		TicketLog ticketLog = new TicketLog();
		for(int j=0;j<15;j++){
			//获取当前系统时间的年月日
			Calendar calendar = Calendar.getInstance();
			calendar.setTimeZone(TimeZone.getTimeZone("GMT+0"));//转为中国时间
			calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 0, 0, 0);
			calendar.set(Calendar.MILLISECOND, 0);//毫秒
			calendar.add(Calendar.DATE, j);
			List<TicketLog> ticketLogs=orderDao.searchLogById(calendar.getTime());
			if(ticketLogs==null || ticketLogs.size()==0){
				int i=0;
				String ticketNos="";
				if(tickets!=null && tickets.size()>0){
					System.out.println("--------------------开始投放共"+tickets.size()+"---------------------");
					for (Ticket ticket : tickets) {
						//将当前系统时间的年月日与ticket的时分秒拼接
						try {
							long time = calendar.getTimeInMillis()+ticket.getStartTime().getTime();
							TicketOrder ticketOrder = new TicketOrder();
							ticketOrder.setId(UUIDUtils.getUUID());
							ticketOrder.setTicketId(ticket.getTicketId());
							ticketOrder.setStartTime(new Date(time));
							ticketOrder.setTicketNumber(ticket.getTicketNumber());
							ticketOrder.setTicketPrice(ticket.getTicketPrice());
							ticketOrder.setCreateTime(new Date());
							boolean flag=orderDao.insert(ticketOrder);
							if(flag){
								i++;
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							ticketNos=ticketNos+ticket.getTicketNo()+",";//?
						}			
					}
					ticketLog.setPutDate(calendar.getTime());
					ticketLog.setTotal(tickets.size());
					ticketLog.setSuccessCount(i);
					ticketLog.setFailCount(tickets.size()-i);
					ticketLog.setFailTicket(ticketNos);
					ticketLog.setCreateTime(new Date());
					orderDao.insertLog(ticketLog);	
					System.out.println("--------------------结束投放，成功"+ticketLog.getSuccessCount()+"失败"+ticketLog.getFailCount()+"失败列车编号为："+ticketLog.getFailTicket()+"---------------------");
				}
			}	
		}
	}
	
}
